package cn.willbj.brief.hootl.lock.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo02 implements Runnable{

	 // 定义火车票
    private int tickets = 200;
    // 定义锁对象
    private Lock lock = new ReentrantLock();
    @Override
    public void run() {
 
        while (true) {
            try {
                // 加锁
                lock.lock();
                //***************业务处理******************
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()
                            + "正在出售第" + (tickets--) + "张票");
                }else {
                    break;
                }
                //*****************************************
            }finally {
                 // 释放锁
                 lock.unlock();
            }
        }
    }
    
   
    
    public static void main(String[] args) {
    	//test01();
		test02();
	}
    private static void test02(){
    	BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(16);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 100, TimeUnit.SECONDS, workQueue, new ThreadPoolExecutor.CallerRunsPolicy());
		
		Demo02 demo02 = new Demo02();
		for (int i = 0; i < 10; i++) {
			executor.execute(demo02);
        }
		
		//终止线程池
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
    
    private static void test01(){
    	BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(16);
		ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 10, TimeUnit.SECONDS, workQueue);
		
		Demo02 demo02 = new Demo02();
		for (int i = 0; i < 10; i++) {
			executor.execute(demo02);
        }
		
		//终止线程池
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}
